package com.servlet;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.commons.Constants;
import com.exception.UserNotFoundException;
import com.service.UserLoginService;
import com.service.UserLoginServiceImpl;

import vo.User;

/**
 * Servlet implementation class UserLoginServlet
 */
@WebServlet("/login.do")
public class UserLoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet() 
     */
    public UserLoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		String code=request.getParameter("code");//用户输入的验证码
		try {
			HttpSession session=request.getSession();
			//获得系统生成的验证码
			String codeTemp=(String)session.getAttribute(Constants.VALIDATE_CODE_KEY);
				//验证码的校验
				if(codeTemp.equals(code)){
				UserLoginService loginservice=new UserLoginServiceImpl();
				User user=loginservice.userLogin(username, password);
				//建立客户端与服务端的会话状态，为以后实现必须先登录后操作的功能做铺垫
				
				session.setAttribute(Constants.USER_SESSION_KEY, user);
				//实现一个用户只能在一处登录
				ServletContext sc=this.getServletContext();
				HttpSession temp=(HttpSession)sc.getAttribute(user.getUserid()+"");
				if(temp!=null) {
					//如果在别处登录过，则将在别处的登录挤掉
					sc.removeAttribute(user.getUserid()+"");
					//如果session已经超时被销毁，则这时会造成重复销毁的问题。解决该问题可以设置一个Listener来监听session的生命周期
					temp.invalidate();
				}
				sc.setAttribute(user.getUserid()+"", session);
				//使用重定向方式跳转到首页 
				response.sendRedirect("main.jsp");
			}else {
				request.setAttribute(Constants.REQUEST_MSG, "验证码有误，请重新输入");
				request.getRequestDispatcher("login.jsp").forward(request, response);
			}
			
		}catch(UserNotFoundException e) {
			request.setAttribute(Constants.REQUEST_MSG, e.getMessage());
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}catch(Exception e) {
			e.printStackTrace();
			response.sendRedirect("error.jsp");
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
